import { Component, OnInit } from '@angular/core';
import {ModalController, NavController, AlertController} from '@ionic/angular';
import { CalendarModelComponent } from '../../../components/calendar-model/calendar-model.component';
import { HttpService } from 'src/app/service/http.service';
import { ActivatedRoute } from '@angular/router';
import { WechatService } from 'src/app/service/wechat.service';
import { TranslateService } from '@ngx-translate/core';
import {Device} from '@ionic-native/device/ngx';
import {ToastService} from '../../../service/toast.service';

@Component({
    selector: 'app-patient-registion-times',
    templateUrl: './patient-registion-times.page.html',
    styleUrls: ['./patient-registion-times.page.scss'],
})
export class PatientRegistionTimesPage implements OnInit {
    doctorId = '';
    paymentOrder: any = {};
    dataList = [];
    weekDays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
    selectValue = '';
    appointDate = null;
    sysLang = '';
    showPatientLogin = true;

    constructor(
        private modalController: ModalController,
        private httpService: HttpService,
        private activatedRoute: ActivatedRoute,
        private wechatSrv: WechatService,
        private navCtrl: NavController,
        private translate: TranslateService,
        private device: Device,
        private alertController: AlertController,
        private toastService: ToastService
    ) {
        activatedRoute.queryParams.subscribe(async queryParams => {
            if (!!queryParams.doctorId) {
                this.doctorId = queryParams.doctorId;
                await this.getAllData();
            }
        });
    }

    ngOnInit() {
        this.sysLang = this.translate.getBrowserCultureLang().toLowerCase();
    }

    public async onResetOrderList() {
        this.appointDate = null;
        await this.getAllData();
    }

    private async getAllData() {
        const queryParams: any = {
            userId: this.doctorId,
            orderBooking: 1,
            patientQuery: true
        };

        // queryParams.queryDate = this.httpService.getDatetimeString();
        queryParams.queryDate = this.httpService.getTomorrowDateString();
        queryParams.timezoneOffset = this.httpService.getTimezoneOffset();

        if (this.appointDate) {
            queryParams.appointDate = this.httpService.getDateString(this.appointDate);
        }

        const result: any = await this.httpService.get()
            .setPath('/pub/order/orderList')
            .setQuery(queryParams)
            .request();
        if (result.status === 0) {
            this.dataList = result.data;
        }
    }

    public async selectDate() {
        this.selectValue = '';
        const modal = await this.modalController.create({
            component: CalendarModelComponent,
            componentProps: {
                title: 'SelectDate',
                timeRange: false,
                patientQuery: true
            }
        });
        await modal.present();
        const { data } = await modal.onDidDismiss();
        if (!!data) {
            this.appointDate = data;
            await this.getAllData();
        }
    }

    public async selectList() {

    }

    public async onItemSelect(item) {
        this.paymentOrder = item;
    }

    private async getBootOptions() {
        const result: any = await this.httpService.get()
            .setPath('/pub/user/getBootOptions')
            .request();

        if (result.status === 0) {
            this.showPatientLogin = result.data.showPatientLogin;
        }
    }

    public async onWxPaymentRequest() {
        const applyUserId = localStorage.getItem('userId');
        const alertData = {
            'en-us': {
                header: 'Alert',
                message: 'Login/Register to appointment',
                cancelText: 'Cancel',
                okText: 'Next'
            },
            'zh-cn': {
                header: '提示',
                message: '登录/注册后才能预约',
                cancelText: '取消',
                okText: '立即前往'
            }
        };

        if (!applyUserId) {
            const alert = await this.alertController.create({
                header: alertData[this.sysLang].header,
                message: alertData[this.sysLang].message,
                buttons: [
                    {
                        text: alertData[this.sysLang].cancelText,
                        role: 'cancel',
                        cssClass: 'secondary',
                        handler: (blah) => {
                            console.log('Confirm Cancel: blah');
                        }
                    }, {
                        text: alertData[this.sysLang].okText,
                        handler: async () => {
                            await this.getBootOptions();

                            await this.navCtrl.navigateForward('/patient-login', {
                                queryParams: {
                                    loginForAppoint: true,
                                    showPatientLogin: this.showPatientLogin
                                }
                            });
                        }
                    }
                ]
            });
            await alert.present();
        } else {
            const englishName = localStorage.getItem('englishName');
            if (!englishName) {
                const toastMessage = {
                    'en-us': 'Please perfect your English name',
                    'zh-cn': '请完善您的英文名'
                };
                return this.toastService.showToast(toastMessage[this.sysLang]);
            }

            if (this.paymentOrder.order_cost === 0) {
                const result: any = await this.httpService.put()
                    .setPath('/order/booking/' + this.selectValue)
                    .setBody({ patientUserId: applyUserId })
                    .request();
                if (result.status === 0) {
                    await this.navCtrl.navigateRoot('/patient-app');
                }
            } else if (this.device.platform) {
                try {
                    const prepayResult = await this.unifiedOrderRequest();
                    await this.wechatSrv.wechatPaymentRequest(prepayResult);
                    await this.updateOrderPayment(prepayResult.trade_code);
                    const result: any = await this.httpService.put()
                        .setPath('/order/booking/' + this.selectValue)
                        .setBody({ patientUserId: applyUserId })
                        .request();
                    if (result.status === 0) {
                        await this.navCtrl.navigateRoot('/patient-app');
                    }
                } catch (e) {
                    if (HttpService.EnvIndex < 2) {
                        alert(JSON.stringify(e));
                    }
                }
            } else {
                alert('wechat must be native');
            }
        }
    }

    private async unifiedOrderRequest() {
        const aUserId = localStorage.getItem('userId');
        const result: any = await this.httpService.post()
            .setPath('/order/wxUnifiedOrder')
            .setBody({
                orderId: this.paymentOrder.id,
                paymentPrice: this.paymentOrder.order_cost,
                patientUserId: aUserId
            })
            .request();

        if (result.status === 0) {
            return result.data;
        } else {
            throw new Error(result.message);
        }
    }

    private async updateOrderPayment(tradeCode) {
        const result: any = await this.httpService.get()
            .setPath('/order/wxQueryOrder')
            .setQuery({
                tradeCode
            })
            .request();

        if (result.status === 0) {
            return result.data;
        } else {
            throw new Error(result.message);
        }
    }
}
